/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.gate.service;

import lombok.extern.slf4j.Slf4j;
import org.cshoo.tattoo.gate.entity.Authority;
import org.cshoo.tattoo.gate.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 杨翼
 * @since 1.0
 */
@Slf4j
@Service
public class MyReactiveUserDetailService implements ReactiveUserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        User user = userService.findByUsername(username);
        if (Objects.isNull(user)) {
            return Mono.empty();
        }
        List<Authority> authorities = userService.findAuthoritiesByUserId(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        authorities.forEach(aut -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(aut.getMethod() + "|" + aut.getUri());
            grantedAuthorities.add(grantedAuthority);
        });
        org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
        return Mono.justOrEmpty(org.springframework.security.core.userdetails.User.withUserDetails(userDetails).build());
    }
}
